package com.hassean.we.admin.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.hassean.we.admin.common.constant.CommonConstant;
import com.hassean.we.admin.common.util.Query;
import com.hassean.we.admin.common.util.R;
import com.hassean.we.admin.common.web.BaseController;
import com.hassean.we.admin.model.entity.TbCall;
import com.hassean.we.admin.model.entity.TbMessage;
import com.hassean.we.admin.model.entity.TbSimInfo;
import com.hassean.we.admin.model.entity.TbTerminal;
import com.hassean.we.admin.service.TbCallService;
import com.hassean.we.admin.service.TbSimInfoService;
import com.hassean.we.admin.service.TbTerminalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yajun
 * @since 2019-03-29
 */
@Api(description = "通话记录接口")
@RestController
@RequestMapping("/tbCall")
public class TbCallController extends BaseController {
    @Autowired private TbCallService tbCallService;
    @Autowired private TbTerminalService tbTerminalService;
    @Autowired private TbSimInfoService tbSimInfoService;
    /**
    * 通过ID查询
    *
    * @param id ID
    * @return TbCall
    */
    @ApiOperation(value = "通过id查询" ,  notes="通过id查询")
    @GetMapping("/{id}")
    public R<TbCall> get(@PathVariable Long id) {
        return new R<>(tbCallService.selectById(id));
    }


    /**
    * 分页查询信息
    *
    * @param params 分页对象
    * @return 分页对象
    */
    @ApiOperation(value = "分页查询" ,  notes="分页查询")
    @RequestMapping("/page")
    public R<Map<String, Object>>getTbCallPage(@RequestParam Map<String, Object> params) {
        params.put(CommonConstant.DEL_FLAG, CommonConstant.STATUS_NORMAL);
        List< Map<String, Object>> resultList = new ArrayList<>();
        Map<String,Object>resultMap = new HashMap<>();

        if (params.get("page")!=null&&!(params.get("page")).equals("")){
            Integer page = Integer.parseInt(params.get("page").toString());
            params.put("page",page);
        }else{
            Integer page = 1;
            params.put("page",page);
        }

        if (params.get("limit")!=null&&!(params.get("limit")).equals("")){
            Integer limit = Integer.parseInt(params.get("limit").toString());
            System.out.println("limit:"+limit);
        }else{
            Integer limit = 10;
            params.put("limit",limit);
        }
        if (params.get("callingPhone")!=null&&!(params.get("callingPhone")).equals("")){
            String callingPhone = params.get("callingPhone").toString();//主叫电话号码
            params.remove("callingPhone");
            //通过电话号码获取终端
            List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(callingPhone);
            //获取主叫终端id
            if(!list.isEmpty()){

                params.put("calling_terminal_id",list.get(0).get("terminal_id"));
            }

        }
        if (params.get("passivityPhone")!=null&&!(params.get("passivityPhone")).equals("")){
            String passivityPhone = params.get("passivityPhone").toString();//被叫电话号码
            params.remove("passivityPhone");
            //通过电话号码获取终端
            List<Map<String, Object>> list = tbTerminalService.selectTerminalIdByPhone(passivityPhone);
            //获取被叫终端id
            if(!list.isEmpty()){

                params.put("passivity_terminal_id",list.get(0).get("terminal_id"));
            }

        }
        Page<TbCall> page = tbCallService.selectPage(new Query<>(params), new EntityWrapper<>());
        for (int i = 0; i <page.getRecords().size() ; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("callId",page.getRecords().get(i).getCallId());
            map.put("duration",page.getRecords().get(i).getDuration());
            map.put("duration",page.getRecords().get(i).getDuration());
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String addTime = sdf.format(page.getRecords().get(i).getAddTime());
            map.put("addTime",addTime);
            map.put("state",page.getRecords().get(i).getState());
            map.put("temp",page.getRecords().get(i).getTemp());
            map.put("status",page.getRecords().get(i).getStatus());
            map.put("remark",page.getRecords().get(i).getRemark());
            map.put("advanceText",page.getRecords().get(i).getAdvanceText());
            map.put("advanceDate",page.getRecords().get(i).getAdvanceDate());
            map.put("delFlag",page.getRecords().get(i).getDelFlag());
            Long callingTerminalId = page.getRecords().get(i).getCallingTerminalId();//主叫终端ID
            Long passivityTerminalId = page.getRecords().get(i).getPassivityTerminalId();//被呼终端ID
            if(callingTerminalId!=null){
                TbTerminal callingTerminal =   tbTerminalService.selectById(callingTerminalId);
                if(callingTerminal!=null){
                    map.put("callingTerminal",callingTerminal);//主叫终端
                    Long simInfoId = callingTerminal.getSimInfoId();
                    TbSimInfo tbSimInfo =  tbSimInfoService.selectById(simInfoId);
                    map.put("callingPhone",tbSimInfo.getSimNumber());//主叫电话号码
                }
            }
            if (passivityTerminalId!=null){
                TbTerminal passivityTerminal =   tbTerminalService.selectById(passivityTerminalId);
                if(passivityTerminal!=null){
                    map.put("passivityTerminal",passivityTerminal);//被呼终端
                    Long simInfoId = passivityTerminal.getSimInfoId();
                    TbSimInfo tbSimInfo =  tbSimInfoService.selectById(simInfoId);
                    map.put("passivityPhone",tbSimInfo.getSimNumber());//被叫电话号码
                }
            }
            resultList.add(map);
        }
        resultMap.put("total",page.getTotal());//总条数
        resultMap.put("size",page.getSize());//每一页多少条
        resultMap.put("pages",page.getPages());//总页数
        resultMap.put("current",page.getCurrent());//起始页
        resultMap.put("resultList",resultList);

        return new R<>(resultMap);
    }

    /**
     * 添加
     * @param  tbCall  实体
     * @return success/false
     */
    @ApiOperation(value = "添加通话记录" ,  notes="添加通话记录")
    @PostMapping
    public R<Boolean> add(@RequestBody TbCall tbCall) {
        return new R<>(tbCallService.insert(tbCall));
    }

    /**
     * 删除
     * @param id ID
     * @return success/false
     */
    @ApiOperation(value = "删除通话记录" ,  notes="删除通话记录")
    @DeleteMapping("/{id}")
    public R<Boolean> delete(@PathVariable Long id) {
        TbCall tbCall = new TbCall();
        tbCall.setCallId(id);
        tbCall.setUpdateTime(new Date());
        tbCall.setDelFlag(CommonConstant.STATUS_DEL);
        return new R<>(tbCallService.updateById(tbCall));
    }

    /**
     * 编辑
     * @param  tbCall  实体
     * @return success/false
     */
    @ApiOperation(value = "编辑通话记录" ,  notes="编辑通话记录")
    @PutMapping
    public R<Boolean> edit(@RequestBody TbCall tbCall) {
        tbCall.setUpdateTime(new Date());
        return new R<>(tbCallService.updateById(tbCall));
    }
    /**
     * 处理未处理且救援电话
     */
    @ApiOperation(value = "处理未处理且救援电话" ,  notes="处理未处理且救援电话")
    @RequestMapping("disposeTbCallHelp")
    public R<Boolean> getTbCallHelp(@RequestBody TbCall tbCall) {
        tbCall.setUpdateTime(new Date());
        tbCall.setState(4);//1接通2未接3拒接4已处理5未处理

        return new R<>(tbCallService.updateById(tbCall));
    }
    //获取未处理且救援电话
    @ApiOperation(value = "获取未处理且救援电话" ,  notes="获取未处理且救援电话")
    @RequestMapping("getTbCallHelp")
    public  R<List>  disposeTbMessagebyHelp(){
        EntityWrapper entity = new EntityWrapper<>();
        entity.eq("state",5);//1接通2未接3拒接4已处理5未处理
       // entity.where("state!=5");//1接通2未接3拒接4已处理5未处理
        entity.eq("status",1);//1救援2其他
        List<TbMessage>selectList = tbCallService.selectList(entity);
        return  new R<>(selectList);

    }

}
